package sensors.impl;

import sensors.IWaterMeter;
import util.Configuration;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class RandomWaterMeter implements IWaterMeter {

    private static RandomWaterMeter singleton = null;

    private double meterCount;
    private Random random;

    private RandomWaterMeter() {
        this.random = new Random();
        this.meterCount = Configuration.waterCount;

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                double expectationPerSec = 0.5 / 60 / 60 / 24;  // 期望是0.5t/d
                double consumption = (random.nextDouble() * 0.4 + 0.8) * expectationPerSec;
                meterCount += consumption;

                Configuration.updateKey("waterCount", String.valueOf(meterCount));
            }
        }, 1000, 1000);
    }

    public synchronized static RandomWaterMeter getInstance() {
        if (singleton == null) {
            singleton = new RandomWaterMeter();
        }
        return singleton;
    }

    public double getMeterCount() {
        return meterCount;
    }
}
